﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SMA.cs" company="">
//   
// </copyright>
// <summary>
//   The sma.
// </summary>
// --------------------------------------------------------------------------------------------------------------------


using System;
using System.Collections.Generic;
using System.Linq;
using Systemathics.FrameWork;

namespace Systemathics.Indicators
{

    [Serializable]
    public sealed class SMA : Indicator
    {
        private readonly Queue<Decimal> queue;
        private Decimal mu;
        private Decimal a, b;

        public int Length { get; private set; }

        public SMA(Instrument instr, Data dt, BarType bt, int value, int length): base(instr, dt, bt, value)
        {
            Length = length;
            queue = new Queue<Decimal>(length);
            mu = 0;
            a = new decimal((Length - 1) / (double)Length);
            b = new decimal(1 / (double)Length);
        }

        protected override void Calculate(object price)
        {
            if (price is Bar)
            {
                var bar = price as Bar;
                Calculate(bar.BeginTime, bar.Median);
            }
            else if (price is Quote)
            {
                var quote = price as Quote;
                Calculate(quote.Time, quote.Mid);
            }
            else
            {
                var trade = price as Trade;
                Calculate(trade.Time, trade.Price);
            }
        }

        private void Calculate(DateTime time, Decimal value)
        {
            if (queue.Count < Length)
            {
                queue.Enqueue(value);
                mu = queue.Average();
            }
            else
            {
                mu = a*mu + b*value;
                Add(time, mu);
                IndicatorCalculated(this);
            }
        }
    }
}